angular.module 'wf-tab', ['ionic']

.directive 'wfTab', (tabData, $ionicHistory, $state) ->
    restrict: 'A'
    link: ($scope, $element, $attrs) ->
        fakeEle = angular.element document.createDocumentFragment()
        fakeEle.append '<div class="tabs tab-nav tabs-icon-top tabs-stable"></div>'
        clearOldTab = undefined # 用于清除旧tab上的样式

        # 处理Tab的DOM元素
        _.each tabData, (tab, $index) ->
            fakeEle.children().append """
              <a class="tab-item" idx="#{$index}"
                state="#{tab.state}">
                <i class="icon #{tab.iconOff}"></i>#{tab.title}</a>
            """
        $element.append fakeEle

        innerElement = angular.element _.last($element.children())

        # 设置tab高亮区域
        select = (idx) ->
            if clearOldTab != undefined then clearOldTab()
            ele = angular.element innerElement.children()[idx]
            iEle = ele.children()
            iEle.removeClass tabData[idx].iconOff
            iEle.addClass tabData[idx].iconOn
            iEle.parent().addClass 'active'

            clearOldTab = ->
                iEle.removeClass tabData[idx].iconOn
                iEle.addClass tabData[idx].iconOff
                iEle.parent().removeClass 'active'

        stateName = $state.current.name
        idx = _.findIndex tabData, (tab) -> tab.state == stateName
        if idx != -1 then select idx

        # 为ion-content添加bottom，保证底部不被Tab遮住
        ionContent = _.find $element.children(), (ele) -> ele.tagName == 'ION-CONTENT'
        height = innerElement[0].getClientRects()[0].height # 获取tab高度
        ionContent.style.bottom = "#{height + 1}px"

        # 点击跳转页面
        innerElement.bind 'click', (e) ->
            tagName = e.target.tagName
            if tagName != 'DIV'
                ele = angular.element e.target
                if tagName == 'I' then ele = ele.parent()
                state = ele.attr 'state' # 获取待跳转的state
                return if $state.current.name==state    #重复点击当前tag,限制跳转
                $ionicHistory.nextViewOptions {disableBack: true}
                $state.go state
